package com.academy.student;

import org.json.JSONException;
import org.json.JSONObject;

import com.academy.querystapp.R;
import com.academy.services.BaseService;
import com.academy.services.RequestMethod;
import com.academy.services.ResponseListener;

import com.academy.util.AcademyUtility;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;

public class AskQuestionActivity extends Activity implements OnClickListener,ResponseListener
{
	EditText edtTeacherID,edtQuestion;
	Button btnPost;
	
	
	
	
	String strTeacherID,strQuestion;
	
    public void onCreate(Bundle savedInstanceState)
    {
    	 super.onCreate(savedInstanceState);
    	 getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    	 setContentView(R.layout.ask_question_layout);
    	 initializeViews();
    }
    
    public void initializeViews()
    {
    	edtTeacherID=(EditText) findViewById(R.id.edtTeacherID);
    	edtQuestion=(EditText) findViewById(R.id.edtQuestion);
    	btnPost=(Button) findViewById(R.id.btnPost);
    	btnPost.setOnClickListener(this);
    }

	@Override
	public void onClick(View v) 
	{
		strTeacherID=edtTeacherID.getText().toString().trim();
		strQuestion=edtQuestion.getText().toString().trim();
		
		
		if(strTeacherID.equals("") && strQuestion.equals(""))
		{
		
			Builder builder = new Builder(this);
			builder.setTitle("Registration");
			builder.setMessage("Please Enter all the Values!");
			builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
			{
				public void onClick(DialogInterface dialog, int arg1)
				{	
					dialog.dismiss();
				}
			});
			AlertDialog alertDialog = builder.create();
			alertDialog.show();
		}
		else if(strTeacherID.equals(""))
		{
			
			Builder builder = new Builder(this);
			builder.setTitle("Query Post");
			builder.setMessage("Enter the TeacherID !");
			builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
			{
				public void onClick(DialogInterface dialog, int arg1)
				{	
					dialog.dismiss();
				}
			});
			AlertDialog alertDialog = builder.create();
			alertDialog.show();
		}	
		else if(strTeacherID.length()<4||strTeacherID.length()>4)
		{
			
			Builder builder = new Builder(this);
			builder.setTitle("Query Post");
			builder.setMessage("Enter your 4 digit Teacher ID !");
			builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
			{
				public void onClick(DialogInterface dialog, int arg1)
				{	
					dialog.dismiss();
				}
			});
			AlertDialog alertDialog = builder.create();
			alertDialog.show();
		}
//		else if(strName.length()<5 ||strName.length()>10)
//		{
//			errorStatus=false;
//			Builder builder = new Builder(this);
//			builder.setTitle("Registration");
//			builder.setMessage("Enter between 5 to 10 characters your name !");
//			builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
//			{
//				public void onClick(DialogInterface dialog, int arg1)
//				{	
//					dialog.dismiss();
//				}
//			});
//			AlertDialog alertDialog = builder.create();
//			alertDialog.show();
//		}
		else if(strQuestion.equals(""))
		{
			
			Builder builder = new Builder(this);
			builder.setTitle("Query Post");
			builder.setMessage("Enter your Question !");
			builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
			{
				public void onClick(DialogInterface dialog, int arg1)
				{	
					dialog.dismiss();
				}
			});
			AlertDialog alertDialog = builder.create();
			alertDialog.show();
		}	
		else 
		{
			
			BaseService baseService = new BaseService(this,this,RequestMethod.GET);
			baseService.addParam(getString(R.string.PostedTeacherID_param), edtTeacherID.getText().toString().trim());
			baseService.addParam(getString(R.string.StudentQuestion_param), edtQuestion.getText().toString().trim());					
			baseService.addParam(getString(R.string.PostedStudentID_param), AcademyUtility.getStudentID());
			baseService.addParam(getString(R.string.StudentQuestionType_param), "General");
			baseService.addParam(getString(R.string.userType_Param),"AddPost");
			baseService.execute(getString(R.string.addStudentPostURL));
		}
	}
	
	
	private void parseResponse(String response)
	{
		if(response==null ||response.equals("null"))
		{
			Builder builder = new Builder(this);
			builder.setMessage("No Server Found!");
			builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
			{
				public void onClick(DialogInterface dialog, int arg1)
				{	
					dialog.dismiss();
				}
			});
			AlertDialog alertDialog = builder.create();
			alertDialog.show();
		}
		else
		{
			try 
			{ 
			
				JSONObject RootObject = new JSONObject(response);
				System.out.println("JSON Object "+RootObject.toString());
				JSONObject queryResultObject = RootObject.getJSONObject("queryResult");
				System.out.println("queryResultObject "+queryResultObject.toString());
				
				System.out.println("Response "+queryResultObject.getString("status"));
				System.out.println("Value of response"+response);
				
				if(queryResultObject.getString("status").equals("false"))
				{
					Builder builder = new Builder(this);
					builder.setTitle("Query Post");
					builder.setMessage(queryResultObject.getString("description"));
					builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
					{
						public void onClick(DialogInterface dialog, int arg1)
						{		
//							edtName.setText("");
//							edtCollegeName.setText("");
//							edtQual.setText("");
//							edtEmailID.setText("");
							edtTeacherID.setText("");
							edtQuestion.setText("");
//							edtPassword.setText("");
//							edtConfirmPassword.setText("");			
							dialog.dismiss();
						}
					});
					AlertDialog alertDialog = builder.create();
					alertDialog.show();	 
				}
				else if(queryResultObject.getString("status").equals("true"))
				{
					
					Builder builder = new Builder(this);
					builder.setTitle("Query Post");
					builder.setMessage(queryResultObject.getString("description"));
					builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
					{
						public void onClick(DialogInterface dialog, int arg1)
						{		
//							edtName.setText("");
//							edtCollegeName.setText("");
//							edtQual.setText("");
//							edtEmailID.setText("");
							edtTeacherID.setText("");
							edtQuestion.setText("");
//							edtPassword.setText("");
//							edtConfirmPassword.setText("");			
							dialog.dismiss();
						}
					});
					AlertDialog alertDialog = builder.create();
					alertDialog.show();
					
				}
		  }
		  catch (JSONException e) 
		  {
			  e.printStackTrace();
		  } 
		}
	}
	
	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {

	    View v = getCurrentFocus();
	    boolean ret = super.dispatchTouchEvent(event);

	    if (v instanceof EditText) {
	        View w = getCurrentFocus();
	        int scrcoords[] = new int[2];
	        w.getLocationOnScreen(scrcoords);
	        float x = event.getRawX() + w.getLeft() - scrcoords[0];
	        float y = event.getRawY() + w.getTop() - scrcoords[1];

	        Log.d("Activity", "Touch event "+event.getRawX()+","+event.getRawY()+" "+x+","+y+" rect "+w.getLeft()+","+w.getTop()+","+w.getRight()+","+w.getBottom()+" coords "+scrcoords[0]+","+scrcoords[1]);
	        if (event.getAction() == MotionEvent.ACTION_UP && (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w.getBottom()) ) { 

	            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
	            imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
	        }
	    }
	return ret;
	}

	@Override
	public void onServiceCompleted(String response, String requestURL) {
		parseResponse(response);
		
	}

	@Override
	public void onServiceFailed(String exception, String requestURL) {
		// TODO Auto-generated method stub
		
	}
	// QueryPost TestCase
	public Boolean QueryPostTestCaseValidation(String Description)
	{
		Boolean validate=false;		
		if(Description.equals("success"))
		{
			System.out.println("Query Posted");
			validate=true;
		}
		else if(Description.equals("failure"))
		{
			System.out.println("Query postig failed");
			validate=false;
		}
		return validate;
	}

	
//	public void onBackPressed() 
//	{
//	   Intent back=new Intent(getApplicationContext(),StudentActivity.class);
//	   startActivity(back);
//	   this.finish();
//	}

}
